class ApiSectionView {
    constructor(container, model) {
        this.container = container;
        this.model = model;
        this.init();
    }

    init() {
        this.bindEvents();
        this.render();
    }

    bindEvents() {
        this.container.addEventListener('change', (e) => {
            if (e.target.matches('.api-option input[type="checkbox"]')) {
                this.handleApiCheckboxChange(e);
            } else if (e.target.matches('.reason-option input[type="checkbox"]')) {
                this.handleReasonCheckboxChange(e);
            }
        });
    }

    handleApiCheckboxChange(e) {
        const apiId = e.target.id;
        const reasonsContainer = this.container.querySelector(`.api-reasons[data-for="${apiId}"]`);
        
        if (e.target.checked) {
            this.showReasons(apiId, reasonsContainer);
        } else {
            this.hideReasons(apiId, reasonsContainer);
        }
    }

    handleReasonCheckboxChange(e) {
        const apiId = e.target.closest('.api-reasons').dataset.for;
        const reasons = Array.from(
            this.container.querySelectorAll(`.api-reasons[data-for="${apiId}"] input:checked`)
        ).map(input => input.id.split('-')[0]);
        
        if (reasons.length > 0) {
            this.model.addAPI(apiId, reasons);
        } else {
            this.model.removeAPI(apiId);
        }
    }

    showReasons(apiId, container) {
        if (!container) return;
        
        const api = this.model.apiReasons[apiId];
        if (api && api.reasons) {
            container.innerHTML = this.generateReasonsHTML(api.reasons, apiId);
            container.style.display = 'block';
            requestAnimationFrame(() => container.classList.add('show'));
        }
    }

    hideReasons(apiId, container) {
        if (!container) return;
        
        container.classList.remove('show');
        setTimeout(() => {
            container.style.display = 'none';
            container.innerHTML = '';
        }, 300);
        
        this.model.removeAPI(apiId);
    }

    generateReasonsHTML(reasons, apiId) {
        return `
            <div class="reason-options">
                ${reasons.map(reason => `
                    <div class="reason-option">
                        <input type="checkbox" id="${reason.code}-${apiId}" name="api-reason">
                        <label for="${reason.code}-${apiId}">
                            <code>${reason.code}</code>
                            <span class="reason-text">
                                <span class="zh">${reason.zh}</span>
                                <span class="en">${reason.en}</span>
                            </span>
                            <div class="reason-note">${reason.note}</div>
                        </label>
                    </div>
                `).join('')}
            </div>
        `;
    }

    render() {
        // 初始渲染逻辑
    }
}

export default ApiSectionView; 